package com.rocksea.app.db.StaticLoad;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;

import android.database.sqlite.SQLiteDatabase;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBaseConfig;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.SQLiteHelper;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.litesuits.orm.db.model.ColumnsValue;
import com.litesuits.orm.db.model.ConflictAlgorithm;
import com.rocksea.app.db.DbCenter;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Mrw on 2017/8/13.
 *
 */

public class StaticLoadDb implements SQLiteHelper.OnUpdateListener {


    private static StaticLoadDb mStaticLoadHelper;
    private static LiteOrm mStaticLoadDb;


    private StaticLoadDb(Context mContext)
    {
        DataBaseConfig config = new DataBaseConfig(mContext);
        config.dbName = Environment.getExternalStorageDirectory().getPath()+"/RailDatabase/db/StaticLoad.db";
        config.dbVersion = 1;
        config.onUpdateListener = this;
        //config.debugged = true;
        mStaticLoadDb = LiteOrm.newCascadeInstance(config);

        StaticLoad staticLoad = new StaticLoad();
        staticLoad.mStaticLoadLog = new ArrayList<>();
        staticLoad.mStaticLoadLog.add(new StaticLoad.StaticLoadLog());
        staticLoad.mStaticLoadTest = new ArrayList<>();
        staticLoad.mStaticLoadTest.add(new StaticLoad.StaticLoadTest());
        mStaticLoadDb.insert(staticLoad);
        mStaticLoadDb.delete(staticLoad);
    }

    @Override
    public void onUpdate(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        String sql = "Alter table "+"StaticLoad"+" add column "+"inspectionFormId"+" TEXT ";
        db.execSQL(sql);
        sql = "Alter table "+"StaticLoad"+" add column "+"pileId"+" TEXT ";
        db.execSQL(sql);
        sql = "Alter table "+"StaticLoad"+" add column "+"inspectionFormNum"+" TEXT ";
        db.execSQL(sql);
    }



    public static StaticLoadDb getInstance(Context mContext) {
        if (mStaticLoadHelper == null){
            synchronized (StaticLoadDb.class)
            {
                mStaticLoadHelper = new StaticLoadDb(mContext);
            }
        }
        return mStaticLoadHelper;
    }


    public int queryVailSampleDataCount(String baseInfoId)
    {
        String sql = "select validDataCount from StaticLoad where baseInfoId = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int count = cursor.getInt(cursor.getColumnIndex("validDataCount"));
            cursor.close();
            return count;
        }
        cursor.close();
        return 0;
    }

    public int queryVailLogDataCount(String baseInfoId)
    {
        String sql = "select validLogCount from StaticLoad where baseInfoId = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int count = cursor.getInt(cursor.getColumnIndex("validLogCount"));
            cursor.close();
            return count;
        }
        cursor.close();
        return 0;
    }

    public void insert(StaticLoad.StaticLoadLog staticLoadLog)
    {
        int count = queryVailLogDataCount(staticLoadLog.baseInfoId);
        if (!isLogExit(staticLoadLog.uuid))
        {
            mStaticLoadDb.insert(staticLoadLog);
            upDateStaticLoadLogVailData(staticLoadLog.baseInfoId,count+1);
        }
    }

    public void insert(StaticLoad.StaticLoadTest staticLoadTest)
    {
        int count = queryVailSampleDataCount(staticLoadTest.baseInfoId);

        if (!isSampleExit(staticLoadTest.uuid))
        {
            mStaticLoadDb.insert(staticLoadTest);
            upDateStaticLoadSampleVailData(staticLoadTest.baseInfoId,count+1);
        }
    }


    public void insert(StaticLoad mStaticLoad)
    {
        mStaticLoadDb.insert(mStaticLoad);
    }

    private void upDateStaticLoadSampleVailData(String baseInfoId,int count)
    {
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isTesting","validDataCount","isLoad","upLoadTime"},new Object[]{0,count,0,0});
        mStaticLoadDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
        DbCenter.mHistoryDbHelper.makeUnUpLoad(baseInfoId);
    }

    private void upDateStaticLoadLogVailData(String baseInfoId,int count)
    {
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isTesting","validLogCount","isLoad","upLoadTime"},new Object[]{0,count,0,0});
        mStaticLoadDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
        DbCenter.mHistoryDbHelper.makeUnUpLoad(baseInfoId);
    }


    public StaticLoad queryById(String baseInfoId)
    {
        QueryBuilder<StaticLoad> queryBuilder = new QueryBuilder<>(StaticLoad.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.where("baseInfoId = ?",baseInfoId);
        queryBuilder.where(whereBuilder);
        ArrayList<StaticLoad> staticLoads = mStaticLoadDb.query(queryBuilder);
        if (staticLoads.size()==0)
            return null;
        if (staticLoads.get(0).mStaticLoadTest==null)
        {
            staticLoads.get(0).mStaticLoadTest = querySampleById(baseInfoId);
        }
        if (staticLoads.get(0).mStaticLoadLog==null)
        {
            staticLoads.get(0).mStaticLoadLog = queryLogByBaseInfoId(baseInfoId);
        }
        return staticLoads.get(0);


    }

    public ArrayList<StaticLoad> queryAll()
    {
        return mStaticLoadDb.query(StaticLoad.class);
    }

    public long queryIsExist(int remoteId)
    {
        QueryBuilder<StaticLoad> queryBuilder = new QueryBuilder<>(StaticLoad.class);
        queryBuilder.where("remoteId=?",remoteId);
        return mStaticLoadDb.queryCount(queryBuilder);
    }



    public ArrayList<StaticLoad.StaticLoadTest> querySampleById(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadTest> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadTest.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.where("baseInfoId = ?",baseInfoId);
        queryBuilder.where(whereBuilder);
        return mStaticLoadDb.query(queryBuilder);
    }

    public void makeAdUpLoad(String baseInfoId)
    {
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        mStaticLoadDb.update(whereBuilder,columnsValue, ConflictAlgorithm.Fail);
    }





    public void makeBaseInfoAsUpLoad(String baseInfoId)
    {
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("uuid",baseInfoId);
        mStaticLoadDb.update(whereBuilder,columnsValue, ConflictAlgorithm.Fail);
    }

    public void makeLogAsUpLoad(String baseInfoId)
    {
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        whereBuilder.andEquals("uuid",baseInfoId);
        mStaticLoadDb.update(whereBuilder,columnsValue, ConflictAlgorithm.Fail);
    }

    public void makeSampleAsUpLoad(String baseInfoId)
    {
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        whereBuilder.andEquals("uuid",baseInfoId);
        mStaticLoadDb.update(whereBuilder,columnsValue, ConflictAlgorithm.Fail);
    }

    public void delete(String baseInfoId)
    {
        WhereBuilder sampleWhereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        sampleWhereBuilder.where("baseInfoId = ?",new Object[]{baseInfoId});
        mStaticLoadDb.delete(sampleWhereBuilder);

        WhereBuilder logwhereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        logwhereBuilder.where("baseInfoId = ?",new Object[]{baseInfoId});
        mStaticLoadDb.delete(logwhereBuilder);

        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.where("baseInfoId = ?",new Object[]{baseInfoId});
        mStaticLoadDb.delete(whereBuilder);
    }

    public ArrayList<StaticLoad.StaticLoadLog> queryLogByBaseInfoId(String basicInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadLog> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadLog.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        whereBuilder.where("baseInfoId = ?",basicInfoId);
        queryBuilder.where(whereBuilder);
        return mStaticLoadDb.query(queryBuilder);
    }

    public void insertServiceId(String baseInfoId,int code)
    {
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"serviceId"},new Object[]{code});
        mStaticLoadDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
    }

    public int queryServiceId(String baseInfoId)
    {
        String sql = "select serviceId from StaticLoad where baseInfoId = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int serviceId = cursor.getInt(cursor.getColumnIndex("serviceId"));
            cursor.close();
            return serviceId;
        }
        cursor.close();
        return -1;

    }

    public int querySampleCounts(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadTest> loadTestQueryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadTest.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        loadTestQueryBuilder.where(whereBuilder);
        return  (int)mStaticLoadDb.queryCount(loadTestQueryBuilder);
    }

    public int queryLogCounts(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadLog> loadTestQueryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadLog.class);
        loadTestQueryBuilder.whereEquals("baseInfoId",baseInfoId);
        return (int)mStaticLoadDb.queryCount(loadTestQueryBuilder);
    }

    public ArrayList<StaticLoad.StaticLoadTest> queryUnLoadSample(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadTest> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadTest.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        whereBuilder.andEquals("upLoadTime",0);
        queryBuilder.where(whereBuilder);
        return mStaticLoadDb.query(queryBuilder);
    }

    public long queryUnLoadSampleCount(String baseInfoId)
    {
        //String sql = "select COUNT() isTesting from StaticLoad where baseInfoId = ? AND upLoadTime = 0";
        QueryBuilder<StaticLoad.StaticLoadTest> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadTest.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        whereBuilder.andEquals("upLoadTime",0);
        queryBuilder.where(whereBuilder);
        return (int)mStaticLoadDb.queryCount(queryBuilder);

    }

    public ArrayList<StaticLoad.StaticLoadLog> queryUnLoadLog(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadLog> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadLog.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        whereBuilder.andEquals("upLoadTime",0);
        queryBuilder.where(whereBuilder);
        return mStaticLoadDb.query(queryBuilder);
    }

    public long queryUnLoadLogCount(String baseInfoId)
    {
        QueryBuilder<StaticLoad.StaticLoadLog> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadLog.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        whereBuilder.andEquals("upLoadTime",0);
        queryBuilder.where(whereBuilder);
        return mStaticLoadDb.queryCount(queryBuilder);
    }


    public void makeTestIsOver(String baseInfoId)
    {
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isTesting"},new Object[]{1});
        mStaticLoadDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
    }

    public void makeTesting(String baseInfoId)
    {
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.class);
        whereBuilder.andEquals("baseInfoId",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isTesting"},new Object[]{0});
        mStaticLoadDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
    }



    public boolean isTesting(String baseInfoId)
    {
        String sql = "select isTesting from StaticLoad where baseInfoId = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int serviceId = cursor.getInt(cursor.getColumnIndex("isTesting"));
            cursor.close();
            return serviceId == 0;
        }
        cursor.close();
        return false;
    }


    public boolean isSampleAndLogUploaded(String baseInfoId)
    {
        return queryUnLoadLogCount(baseInfoId) == 0 && queryUnLoadSampleCount(baseInfoId) == 0;
    }


    public boolean isDataUpLoad(String uuid)
    {
        String sql = "select upLoadTime from StaticLoadTest where uuid = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{uuid});
        if (cursor.moveToFirst())
        {
            Long upLoadTime = cursor.getLong(cursor.getColumnIndex("upLoadTime"));
            cursor.close();
            return upLoadTime > 0;
        }
        cursor.close();
        return false;
    }

    public boolean isLogUpLoad(String uuid)
    {
        String sql = "select upLoadTime from StaticLoadLog where uuid = ?";
        Cursor cursor = mStaticLoadDb.getWritableDatabase().rawQuery(sql,new String[]{uuid});
        if (cursor.moveToFirst())
        {
            long upLoadTime = cursor.getLong(cursor.getColumnIndex("upLoadTime"));
            cursor.close();
            return upLoadTime > 0;
        }
        cursor.close();
        return false;
    }

    public boolean isSampleExit(String sampleUUID)
    {
        QueryBuilder<StaticLoad.StaticLoadTest> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadTest.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadTest.class);
        whereBuilder.andEquals("uuid",sampleUUID);
        queryBuilder.where(whereBuilder);
        return (int)mStaticLoadDb.queryCount(queryBuilder) != 0;
    }

    public boolean isLogExit(String logUUID)
    {
        QueryBuilder<StaticLoad.StaticLoadLog> queryBuilder = new QueryBuilder<>(StaticLoad.StaticLoadLog.class);
        WhereBuilder whereBuilder = new WhereBuilder(StaticLoad.StaticLoadLog.class);
        whereBuilder.andEquals("uuid",logUUID);
        queryBuilder.where(whereBuilder);
        return (int)mStaticLoadDb.queryCount(queryBuilder) != 0;
    }



}
